<?php
/**
 * 训练管理
 */
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Agency;
use App\Models\Child;
use App\Models\History;
use App\Models\User;
use http\Env\Response;
use Illuminate\Http\Request;

class TrainingController extends BaseController
{
    /**
     * 按照平台和学校区分不同，展示不同范围的数据，
     * 显示形式相同。
     *
     * 平台展示所有
     * 学校展示本校学生
     *
     */

    public function index(Request $request){
        $admin = $this->getAdmin();
        $isSchool = $this->isSchool();

        $query = $request->only(['child_name', 'child_id', 'agency_id', 'user_id','startquerytime', 'endquerytime']);
        $users = collect();

        if ($isSchool){
            $query['agency_id'] = $admin->agency->id;
            $users = User::where("agency_id", $admin->agency->id)->get();
        }else{
            if (isset($query['agency_id'])){
                $users = User::where("agency_id", $query['agency_id'])->get();
            }
        }
        if (empty($query['child_name']) && isset($query['child_id'])){
            $query['child_name'] = Child::where('id', $query['child_id'])->value("name");
        }
        //平台
        $where = History::selectQuery($query);

        $list = History::where($where)->orderBy('id', 'desc')->paginate(config('site.other.paginate'));

        $list = $list->appends($query);
        $agencies = Agency::all();

        return backendView('training.index', compact('list', 'isSchool','admin', 'agencies', 'users', 'query'));
    }

    //todo:view
    public function view($id){
        $training = History::find($id);
        if (empty($training)){
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        //dd($training);
        return backendView('training.view', compact('training'));
    }

    public function delete($id){
        $training = History::find($id);
        if (empty($training)){
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($training->delete()) {
            return back()->with('success', __('Delete success'));
        }

        return back()->with('error', __('Delete failed'));
    }
}
